package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.entity.ApArticle;
import com.heima.article.entity.ApArticleContent;
import com.heima.article.entity.ApAuthor;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.service.ApAuthorService;
import com.heima.article.service.FreeMarkerService;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.LeadException;
import com.heima.common.util.BeanHelper;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.article.dtos.ArticleHomeDto;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsResultDTO;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author HM
 * @since 2022-04-29
 */
@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {

    @Autowired
    private ApArticleContentService contentService;

    @Autowired
    private ApAuthorService apAuthorService;

    @Autowired
    private FreeMarkerService freeMarkerService;

    /**
     * 保存文章
     *
     * @param dto
     * @return
     */
    public Long saveArticle(WmNewsResultDTO dto) {
        // 根据自媒体查询文章信息
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getWmNewsId, dto.getId());

        ApArticle apArticle = getOne(queryWrapper);
        // 如果不存在,new 一个新对象
        if (apArticle == null) {
            // 新增才需要
            apArticle = new ApArticle();
            apArticle.setWmNewsId(dto.getId());

            ApAuthor apAuthor = apAuthorService.getByWmUserId(dto.getWmUserId());
            if (apAuthor != null) {
                apArticle.setAuthorId(apAuthor.getId());
                apArticle.setAuthorName(apAuthor.getName());
            }
            apArticle.setCreatedTime(new Date());
            apArticle.setLikes(0L);
            apArticle.setCollection(0L);
            apArticle.setComments(0L);
            apArticle.setViews(0L);
            apArticle.setIsDown(false);
            apArticle.setIsDelete(false);
            apArticle.setIsComment(true);
            apArticle.setIsForward(true);
            apArticle.setFlag(0);
        }
        // 新增修改都需要
        apArticle.setTitle(dto.getTitle());
        apArticle.setChannelId(dto.getChannelId());
        apArticle.setChannelName(dto.getChannelName());
        apArticle.setLayout(dto.getType());
        apArticle.setImages(dto.getImages());
        apArticle.setLabels(dto.getLabels());
        apArticle.setPublishTime(dto.getCreatedTime() == null ? new Date() : dto.getPublishTime());

        // 新增或保存
        boolean b = saveOrUpdate(apArticle);

        if (!b) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
        // 文章id
        Long apArticleId = apArticle.getId();
        ApArticleContent apArticleContent = new ApArticleContent();
        apArticleContent.setArticleId(apArticleId);
        apArticleContent.setContent(dto.getContent());
        // 新增修改 内容表
        boolean b2 = contentService.saveOrUpdate(apArticleContent);

        if (!b2) {
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }

        //生成文章详情的静态页面,写入MinIo
        freeMarkerService.buildContentHtml(apArticle,dto.getContent());
        return apArticleId;
    }

    /**
     * 加载首页
     * @Param status 1 -上拉  2- 下拉
     * @param dto
     * @return
     */
    public List<ArticleDto> load(ArticleHomeDto dto,Integer status) {
        // 构造分页条件
        Page<ApArticle> page = new Page<>(1, dto.getSize());

        // 构造条件
        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(ApArticle::getIsDelete, false).eq(ApArticle::getIsDown, false);

        if (dto.getChannelId() != 0 && dto.getChannelId() != null) {
            queryWrapper.eq(ApArticle::getChannelId, dto.getChannelId());
        }
        // 下拉 最新时间
        if (dto.getMaxTime() != null && status == 2) {
            // 获得新文章
            queryWrapper.gt(ApArticle::getPublishTime, dto.getMaxTime());
        }
        // 上拉 以前时间
        if (dto.getMinTime() != null  && status == 1) {
            // 获得旧文章
            queryWrapper.lt(ApArticle::getPublishTime, dto.getMinTime());
        }
        // 分页
        IPage<ApArticle> apArticleIPage = page(page, queryWrapper);
        // 判断是否查询到数据
        if (apArticleIPage == null || CollectionUtils.isEmpty(apArticleIPage.getRecords())) {
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return BeanHelper.copyWithCollection(apArticleIPage.getRecords(), ArticleDto.class);
    }

    /**
     * 上下架
     *
     * @param map
     */
    public void dowmOrUp(Map<String, Long> map) {
        ApArticle apArticle = new ApArticle();
        apArticle.setId(map.get("articleId"));
        apArticle.setIsDown(map.get("enable") == 1?false: true);

        boolean b = updateById(apArticle);
        if (!b){
            log.error("修改上下架失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }

    /**
     * 分页查询文章数据
     *
     * @param page
     * @param size
     * @return
     */
    public List<ArticleDto> findByPage(Integer page, Integer size) {
        // 构造分页条件
        IPage<ApArticle> Ipage = new Page<>(page,size);

        // 调用mapper 查询数据库
        ApArticleMapper baseMapper = getBaseMapper();

        return baseMapper.findByPage(Ipage);
    }


    /**
     * 根据id 查询自媒体文章
     *
     * @param id
     * @return
     */
    public ArticleDto selectOneArticle(Integer id) {


        LambdaQueryWrapper<ApArticle> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ApArticle::getId,id);

        ApArticle apArticle = getOne(queryWrapper);


        if (apArticle == null){
            log.error("查询自媒体文章失败");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);

        }
        ArticleDto dto = new ArticleDto();

        BeanUtils.copyProperties(apArticle,dto);


        return dto;
    }


    /**
     * 删除自媒体文章
     *
     * @param id
     * @return
     */
    public void deleteByIdArticle(Integer id) {
        ApArticle apArticle = getById(id);
        if (apArticle == null) {
            log.error("没用根据id查询到文章");
            throw new LeadException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        boolean b = removeById(id);

        if (!b){
            log.error("根据id删除失败");
            throw new LeadException(AppHttpCodeEnum.DELETE_NOT_ID);
        }
    }


    /**
     * 审核通过
     *
     * @param
     * @return
     */
    public void saveByWmNewsDto(WmNewsResultDTO dto) {
        ApArticle apArticle = new ApArticle();


        BeanUtils.copyProperties(dto,apArticle);

        apArticle.setAuthorId(dto.getArticleId().intValue());
        if (dto.getAuthorName() != null && dto.getAuthorName() != "") {
            apArticle.setAuthorName(dto.getAuthorName());
        }
        apArticle.setChannelId(dto.getChannelId());
        apArticle.setChannelName(dto.getChannelName());
        apArticle.setImages(dto.getImages());
        apArticle.setLabels(dto.getLabels());
        apArticle.setLikes(0L);
        apArticle.setCollection(0L);
        apArticle.setComments(0L);
        apArticle.setViews(0L);
        apArticle.setCreatedTime(dto.getCreatedTime());
        apArticle.setIsComment(true);
        apArticle.setIsForward(true);
        apArticle.setIsDown(false);
        apArticle.setIsDelete(false);

        apArticle.setWmNewsId(dto.getWmUserId());
        boolean b = save(apArticle);

        if (!b){
            log.error("审核通过,添加到发布表失败");
            throw new LeadException(AppHttpCodeEnum.SERVER_ERROR);
        }
    }
}

